<?php

namespace app\admin\service;

use app\api\service\CommonService;
use app\common\model\Export;
use app\model\AgentBalanceLog as Model;
use think\Collection;

class AgentBalanceLog extends CommonService
{
    public function getTypeNameById($type)
    {
       /* $arr = [
            1 => '提现申请',
            2 => '提现撤销',
            3 => '提现驳回',
            4 => '话费佣金',
            5 => '话费扣款',
            6 => '后台充值',
            7 => '话费充值失败退款',
            8 => '在线充值',
            9 => '加油佣金',
            10 => '权益佣金',
            11 => '影票佣金',
            12 => '权益扣款',
            13 => '影票扣款',
            14 => '预付退款',
            15 => '加油扣款',
            16 => '油卡扣款',
            17 => '电费扣款',
            18 => '油卡佣金',
            19 => '电费佣金',
            20 => '佣金提现',
            21 => '佣金提现申请通过',
            22 => '退款申请',
            23 => '退款申请撤销',
            24 => '退款申请拒绝',
            25 => '退款申请通过',
            26 => '退款完成',
            27 => '退款失败',
            28 => '提现失败',
            29 => '加油卡退款',
            30 => '电费退款',
            31 => '权益退款',
            32 => '影票退款',
            34 => '出行/加油CPS佣金',
            35 => '周边游CPS佣金',
            BALANCE_FOOD_COMMISS => '连锁餐饮CPS佣金',
            BALANCE_MEITUAN_SEACKILL_COMMISS => '美团秒杀CPS佣金',
            BALANCE_TACKOUT => '外卖佣金',
            BALANCE_TACKOUT_ELE => '饿了么外卖佣金',
            BALANCE_TACKOUT_MEITUAN_DAODIAN => '美团到店',   //告诉前端，前端也要加不要漏了 ，不然就会像这样子  https://pic.rmb.bdstatic.com/bjh/4331238188a6d9817d5bdab2da5b2be0.png
            BALANCE_MOBILE_CPS_SERV => 'CPS话费',//CPS话费
        ];*/
        $balance_types = BALANCE_TYPES;
        $arr = array();
        foreach ($balance_types as $key=>$balance_type){
            $arr[$key] = $balance_type['name'];
        }
        return $arr[$type];
    }


    public function flowType($type)
    {
        $list = array();
        $balance_types = BALANCE_TYPES;
        if ($type == 1) { //预付扣款
            $list = array_filter($balance_types, function($t) use ($type) {
                if (isset($t['prepaid_debit']) && $t['prepaid_debit'] == 1) {
                    return $t['prepaid_debit'] == 1;
                }
            });
        } elseif($type == 2) { //充值记录
            $list = array_filter($balance_types, function($t) use ($type) {
                if (isset($t['recharge_record']) && $t['recharge_record'] == 1) {
                    return $t['recharge_record'] == 1;
                }
            });
        } elseif($type == 3) { //佣金明细
            $list = array_filter($balance_types, function($t) use ($type) {
                if (isset($t['commission_details']) && $t['commission_details'] == 1) {
                    return $t['commission_details'] == 1;
                }
            });
        } elseif($type == 4) {//提现记录
            $list = array_filter($balance_types, function($t) use ($type) {
                if (isset($t['embody_record']) && $t['embody_record'] == 1) {
                    return $t['embody_record'] == 1;
                }
            });
        }
        return array_keys($list);
    }

    /*
     获取log
     sum = 0 导出不起作用。0：不做数据统计 1：统计 其他取值自行处理逻辑
     flowType 资金流向
    */
    public function agentIdBalanceTypeLog($agentId, $param, $flowType, $sum = 0, $field = '')
    {
        //dd($this->flowType(3));
        $flowTypeArr = [
            'charge' => [ // 资金的明细
                BALANCE_MOBILE_PROFIT, // 代理商收入
                BALANCE_MOBILE_RECHARGE, // '话费扣款',
                BALANCE_AGENT_RECHARGE, // => '后台充值',
                BALANCE_MOBILE_REFUND, // => '话费充值失败退款',
                BALANCE_ONLINE_RECHARGE, // => '代理商充值',
                BALANCE_OIL_COMMISS, // => '加油佣金',
                BALANCE_COUPON_COMMISS, // => '权益佣金',
                BALANCE_FILM_COMMISS, // => '影票佣金',
                BALANCE_COUPON_EXPENSE, // => '权益扣款',
                BALANCE_FILM_EXPENSE, // => '影票扣款',
                BALANCE_AGENT_REFUND, // => '预付退款',
                BALANCE_OILCARD_EXPENSE, // => '油卡扣款',
                BALANCE_POWER_EXPENSE, // => '电费扣款',
                BALANCE_OILCARD_COMMISS, // => '油卡佣金',
                BALANCE_POWER_COMMISS, // => '电费佣金',
                BALANCE_OILCARD_REFUND, // '加油卡退款',
                BALANCE_POWER_REFUND, // '电费退款',
            ],
            'commission' => [ // 佣金记录 目前用在总后台佣金记录

                BALANCE_WITHDRAW_APPLY,//其实他是有提现的，但是这个whereIn 查询不到这边的记录，所以添加这个https://inews.gtimg.com/newsapp_ls/0/14938944162/0.jiketuchuang.png

                BALANCE_MOBILE_PROFIT,
                BALANCE_OIL_COMMISS,
                BALANCE_COUPON_COMMISS,
                BALANCE_FILM_COMMISS,
                BALANCE_OILCARD_COMMISS,
                BALANCE_POWER_COMMISS,
                BALANCE_TRAVEL_OIL_COMMISS,
                BALANCE_AROUND_COMMISS,
                BALANCE_FOOD_COMMISS,
                BALANCE_MEITUAN_SEACKILL_COMMISS,
                BALANCE_TACKOUT,
                BALANCE_TACKOUT_ELE,
                BALANCE_TACKOUT_MEITUAN_DAODIAN,

            ],
            'serv_commiss' => [ // 佣金收益  目前用在代理商->资金明细->佣金收益 tab
                BALANCE_MOBILE_PROFIT,
                BALANCE_OIL_COMMISS,
                BALANCE_COUPON_COMMISS,
                BALANCE_FILM_COMMISS,
                BALANCE_OILCARD_COMMISS,
                BALANCE_POWER_COMMISS,
                BALANCE_TRAVEL_OIL_COMMISS,
                BALANCE_AROUND_COMMISS,
                BALANCE_FOOD_COMMISS,
                BALANCE_MEITUAN_SEACKILL_COMMISS,
                BALANCE_TACKOUT,
                BALANCE_TACKOUT_ELE,
                BALANCE_TACKOUT_MEITUAN_DAODIAN,
                BALANCE_MOBILE_CPS_SERV,//CPS话费
            ],
            'serv_payout' => [ // 预扣记录 目前用在代理商->资金明细->预扣记录 tab
                BALANCE_MOBILE_RECHARGE,// 话费充值
                BALANCE_MOBILE_REFUND,  // 话费退款
                BALANCE_COUPON_EXPENSE, // 权益卡充值
                BALANCE_COUPON_REFUND,  // 权益卡退款
                BALANCE_FILM_EXPENSE,   // 电影充值
                BALANCE_FILM_REFUND,    // 电影退款
                BALANCE_OILCARD_EXPENSE,// 油卡充值
                BALANCE_OILCARD_REFUND, // 加油退款
                BALANCE_POWER_EXPENSE,  // 电费充值
                BALANCE_POWER_REFUND,   // 电费退款
            ],
            'withdraw' => [ // 提现记录  目前用在代理商->资金明细->提现记录 tab
                BALANCE_WITHDRAW_APPLY,
                BALANCE_WITHDRAW_CANCEL,
                BALANCE_WITHDRAW_REJECT,
            ],
            'recharge' => [ // 账户充值记录  目前用在代理商->资金明细->账户充值记录 tab ，代理商->财务管理->账户充值预付 tab
                BALANCE_AGENT_RECHARGE,
                BALANCE_ONLINE_RECHARGE,
                BALANCE_REFUND_APPLY,
                BALANCE_REFUND_CANCEL,
                BALANCE_REFUND_REJECT,
                BALANCE_CHANGE_APPLY,    // 加款申请
            ],
        ];
        $modelQuery = Model::withJoin(['agent' => function ($query) {
            $query->withField(['agent.company_name' => 'company_name', 'agent.username' => 'username','agent.is_relation'=>'is_relation']);
        }])->whereIn('type', $flowTypeArr[$flowType]);
        // 主表名
        $tableName = $modelQuery->getTable();
        $tableName = array_pop($tableName);

        // step 构造查询
        $where = [
            ['agent_id', '=', $agentId],
        ];
        if (!empty($param['type'])) {
            $where[] = ['type', '=', $param['type']];
        }

        if (!empty($param['trade_no'])) {
            $where[] = ['trade_no', '=', $param['trade_no']];
        }
        if (isset($param['datetime'])) {
            if (!empty($param['datetime']['start'])) {
                $where[] = [$tableName.'.updated_at', '>=', $param['datetime']['start']];
            }
            if (!empty($param['datetime']['end'])) {
                $where[] = [$tableName.'.updated_at', '<=', $param['datetime']['end'] . ' 23:59:59'];
            }
        }

        $modelQuery = $modelQuery->where($where);

        // 导出和列表分页处理
        if (!empty($param['is_export'])) {
            if ($field) {
                $modelQuery = $modelQuery->field($field);
            }
            return $modelQuery->order('id desc')->select();
        } else {
            if ($field) {
                $modelQuery = $modelQuery->field($field);
            }
            $list = $modelQuery->order('id desc')->paginate($param);
            if (!$list->isEmpty()) {
                $list->hidden(['agent']);
            }
            $list = $list->toArray();

            if (1 === $sum) {
                // 获取总计
                $list['sum'] = ['data1' => 0, 'data2' => 0];
                $sumList = $modelQuery->fieldRaw('type,sum(amount) as amount')->group('type')->select();
                if (!$sumList->isEmpty()) {
                    $sumList = $sumList->toArray();
                    //dd($sumList);
                    if ('commission' == $flowType) {
                        foreach ($sumList as $k => $v) {
                            if ($v['type'] == BALANCE_WITHDRAW_APPLY) { // 累计提现
                                $list['sum']['data1'] = $v['amount'];
                            } else {
                                $list['sum']['data2'] += $v['amount'];
                            }
                        }
                    } else {
                        foreach ($sumList as $k => $v) {
                            if (!in_array($v['type'], [BALANCE_AGENT_RECHARGE, BALANCE_ONLINE_RECHARGE, BALANCE_MOBILE_REFUND, BALANCE_AGENT_REFUND])) { // 累计充值+退款
                                $list['sum']['data2'] += $v['amount'];
                            } else {
                                $list['sum']['data1'] += $v['amount'];
                            }
                        }
                    }

                    // 处理成单位 【元】形式
                    foreach ($list['sum'] as $k => $v) {
                        $list['sum'][$k] = fen2yuan($v);
                    }
                }
            } elseif(2 === $sum) {
                $sumList = $modelQuery->fieldRaw('type,sum(amount) as amount')->group('type')->select();
                $count = array();
                if (!$sumList->isEmpty()) {
                    $sumList = $sumList->toArray();
                    if ($flowType == 'serv_payout') {//预付扣款

                        $count['sum']['debit']['total'] = 0;

                    } elseif($flowType == 'withdraw') { //提现记录

                        $count['sum']['apply'] = 0;
                        $count['sum']['reject'] = 0;
                        $count['sum']['withdrawn'] = 0;

                    } elseif($flowType == 'recharge') {//充值记录

                        $count['sum']['online'] = 0;
                        $count['sum']['backstage'] = 0;
                        $count['sum']['addMoney'] = 0;
                        $count['sum']['total'] = 0;

                    } else { //佣金明细-------已组装

                        $count['sum']['total'] = 0;

                    }
                    foreach ($sumList as $v) {
                        if ( $flowType == 'serv_payout') {//预付扣款
                            if ($v['amount'] >= 0) {//退款
                                //总数
                                //$count['sum']['refund']['total'] += $v['amount'];
                                //各个类别的总数
                                $count['sum']['refund'][$v['type']] = fen2yuan($v['amount']);
                            } else { //各个服务累计充值、各个之和就是累计扣款总额
                                //总数
                                $count['sum']['debit']['total'] += abs($v['amount']);
                                //各个类别的总数
                                $count['sum']['debit'][$v['type']] = abs(fen2yuan($v['amount']));
                            }
                        } elseif($flowType == 'withdraw') {//申请提现
                            if ($v['type'] == BALANCE_WITHDRAW_APPLY) { //申请提现总数额

                                $count['sum']['apply'] += abs($v['amount']);

                            } else { //撤销或者拒绝的总数

                                $count['sum']['reject'] += $v['amount'];
                            }
                        } elseif($flowType == 'recharge') {//充值记录
                            if ($v['type'] == BALANCE_ONLINE_RECHARGE) { //累计在线充值金额

                                $count['sum']['online'] += $v['amount'];

                            } elseif($v['type'] == BALANCE_AGENT_RECHARGE) {//累计后台充值金额

                                $count['sum']['backstage'] += $v['amount'];

                            } elseif($v['type'] == BALANCE_CHANGE_APPLY) {//代理商加款申请
                                $count['sum']['addMoney'] += $v['amount'];
                            }
                        } else { //佣金明细 serv_commiss
                            //总数
                            $count['sum']['total'] += $v['amount'];
                            //各个类别的总数
                            $count['sum'][$v['type']] = fen2yuan($v['amount']);
                        }
                    }
                    if ($flowType == 'serv_payout') {  //预付扣款

                        $count['sum']['debit']['total'] = fen2yuan($count['sum']['debit']['total']);

                    } elseif($flowType == 'withdraw'){ //提现记录

                        $count['sum']['withdrawn'] = fen2yuan(bcsub($count['sum']['apply'], $count['sum']['reject']));
                        $count['sum']['apply'] = fen2yuan($count['sum']['apply']);

                        unset($count['sum']['reject']);
                    } elseif($flowType == 'recharge') {//充值记录

                        $count['sum']['online'] = fen2yuan($count['sum']['online']);
                        $count['sum']['backstage'] = fen2yuan($count['sum']['backstage']);
                        $count['sum']['addMoney'] = fen2yuan($count['sum']['addMoney']);
                        $total = bcadd($count['sum']['backstage'], $count['sum']['online'],2);
                        $count['sum']['total'] = bcadd($total, $count['sum']['addMoney'],2);

                    } else { //serv_commiss佣金明细

                        $count['sum']['total'] = fen2yuan($count['sum']['total']);
                    }
                    return $count;
                }
            }
        }
        return $list;
    }

    public function collectionToExcel(Collection $list, array $titleArr, $toExcel = 1)
    {
        if ($list->isEmpty()) {
            $list = [];
        } else {
            // 去除title包含的字段
            $list = $list->toArray();
            //$stateArr = Model::$typeArr;
            $stateArr = Model::getTypeArr();
            foreach ($list as $k => $v) {
                $list[$k]['type'] = $stateArr[$v['type']];
                $list[$k]['amount'] = fen2yuan($v['amount']);
                $list[$k]['old_balance'] = fen2yuan($v['old_balance']);
                $list[$k]['new_balance'] = fen2yuan($v['new_balance']);
            }
        }

        if ($toExcel) {
            return Export::staticExport($list, $titleArr);
        }

        return $list;
    }

    /*
     data 和Export类 的批量导出参数格式一致 [['sheetname'=>'sheet名字','title'=>['id'=>'id','name'=>'名字'],'data'=>[数组]]]
    */
    public function collectionToMulitSheetExcel(array $data, $filename = '')
    {
        foreach ($data as $k => $v) {
            $data[$k]['data'] = $this->collectionToExcel($v['data'], $v['title'], 0);
        }

        return Export::multiSheetExport($data, $filename);
    }

}
